package com.siyoumi.sh.modules.common;

import com.siyoumi.sh.modules.common.send_msg.ISendMsg;
import com.siyoumi.util.*;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HandleBase {
    public void sendMsg(String msg) {
        sendMsg(msg, null);
    }

    public void sendMsg(String msg, String title) {
        ISendMsg sm = ISendMsg.getIns();
        if (sm == null) {
            log.error("未配置发送信息参数");
            return;
        }

        if (XStr.isNullOrEmpty(title)) {
            sm.send(msg);
        } else {
            sm.send(msg, title);
        }
    }

    /**
     * 输出日志并追加字符串
     *
     * @param s
     */
    protected void sleepAndLog(int s) {
        logAndSet(null, "停" + s + "秒", true);
        XApp.sleep(s);
    }

    /**
     * 输出日志并追加字符串
     *
     * @param sb
     * @param msg
     */
    protected void logAndSet(StringBuilder sb, String msg) {
        logAndSet(sb, msg, false);
    }

    protected void logAndSet(StringBuilder sb, String msg, boolean onlyLog) {
        if (!onlyLog) {
            sb.append(msg);
        }
        log.info(msg);
    }

    //请求
    public XReturn requestApi(String url) {
        //添加请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("apixAuth", "1");

        XReturn r;
        try {
            XHttpClient client = XHttpClient.getInstance();
            String returnStr = client.get(url, headers);
            r = XReturn.parse(returnStr);

            log.debug("{},{}", this.getClass(), url);
            log.debug("{},{}", this.getClass(), returnStr);
        } catch (Exception ex) {
            ex.printStackTrace();
            String errmsg = ex.getMessage();
            log.error("{},{}", this.getClass(), errmsg);
            r = XReturn.getR(500, errmsg);
        }

        if (r.ok() && XStr.isNullOrEmpty(r.getErrMsg())) {
            r.setErrMsg("成功");
        }

        return r;
    }
}
